package org.ejc.tech;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.ResourceBundle;

import org.apache.log4j.Logger;
import org.ejc.api.country.CountryAPIUtil;
import org.ejc.persist.model.CountryCode;

public class CountryHandler {

	private static final String PREFIX = "org.ejc.country.";
	private static Logger log = Logger.getLogger(CountryHandler.class);
	static HashMap<String,Collection> map = new HashMap<String,Collection>();

	static {
		// get from DB!
		Locale localeEng = new Locale("en");
		Locale localeFr = new Locale("fr");

		Collection<Locale> locales = new ArrayList<Locale>();
		locales.add(localeEng);
		locales.add(localeFr);

		for (Iterator iter = locales.iterator(); iter.hasNext();) {

			Collection<CountryCode> newCol = new ArrayList<CountryCode>();

			Locale locale = (Locale) iter.next();

			ResourceBundle resource = ResourceBundle.getBundle(
					"org.ejc.resources.Countries", locale);
			try {
				Collection c = CountryAPIUtil.getLocalHome().create()
						.getCountryListing();

				for (Iterator iter1 = c.iterator(); iter1.hasNext();) {
					CountryCode element = (CountryCode) iter1.next();
					String key = PREFIX + element.getCountryIsoCode();
					String localizedName = (String) resource.getObject(key);


					CountryCode code = new CountryCode();
					code.setCountryId(element.getCountryId());
					code.setCountryIsoCode(localizedName);
					newCol.add(code);
				}
			} catch (Exception e) {
				log.fatal("Error in setting up country codes!");
			}
			map.put(locale.getLanguage(), newCol);
		}
	}

	public static Collection getCollection(Locale l) {
		return (Collection) map.get(l.getLanguage());
	}

}
